<?php

namespace App\Http\Controllers\api;

use App\Constant\GroupApplyEnum;
use App\Constant\OrderEnum;
use App\Libraries\Payment\WechatPay\WechatPayPayment;
use App\Models\GroupApply;
use App\Models\Order;
use App\Models\Setting;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PaymentWechatController extends BaseController
{
    public function prepay(Request $request)
    {
        /** @var User $user */
        $user = auth('jwt')->user();

        $type =  GroupApplyEnum::TYPE_NORMAL;
        if (!in_array($type,  [
            GroupApplyEnum::TYPE_NORMAL, GroupApplyEnum::TYPE_ADVANCED
        ])) {
            return $this->error('未选择团长类型');
        }

        $config = Setting::get('group');
        $advancedConfig = Setting::get('advanced_group');
        $chargeFee = $config['price'];
        $enabled = $config['enabled'] ?? 0;
        $orderType = OrderEnum::TYPE_GROUP;
        if ($type == GroupApplyEnum::TYPE_ADVANCED) {
            $chargeFee = $advancedConfig['advanced_price'];
            $orderType = OrderEnum::TYPE_ADVANCED_GROUP;
        }
        if (!$enabled) {
            return $this->error('暂未开通团长渠道');
        }
        if ($user->is_group_leader) {
            return $this->error('已经是团长无需再次开通！');
        }

        $lowestMember = $config['lowest_member'] ?? 0;
        if ($type == GroupApplyEnum::TYPE_ADVANCED) {
            $lowestMember = $advancedConfig['advanced_lowest_member'] ?? 0;
        }

        if (!empty($lowestMember)) {
            $childrenCount = User::query()->where('parent_id', $user->id)->count();

            if ($childrenCount >= $lowestMember) {
                $has = GroupApply::query()->where([
                    'user_id' => $user->id,
                    'type' => $type,
                    'status' => GroupApplyEnum::STATUS_PENDING
                ])->exists();

                if (!$has) {
                    $apply = GroupApply::query()->create([
                        'user_id' => $user->id,
                        'type' => $type,
                        'members' => $childrenCount,
                        'status' => GroupApplyEnum::STATUS_PENDING,
                        'applied_at' => Carbon::now(),
                        'price'=>$config['price'],
                        'days'=>$config['return_days'],
                        'amount'=>$config['return_amount']
                    ]);
                    if ($apply) {
                        return $this->success(['need_pay'=>0],'团长申请已提交');
                    } else {
                        return $this->error('系统繁忙，请稍后再试');
                    }
                } else {
                    return $this->error('团长申请已提交，请勿重复操作！');
                }
            }
        }

        if (empty($chargeFee)) {
            return $this->error("暂未满足开通团长条件");
        }

        $check = Order::query()
            ->where([
                'user_id' => $user->id,
                'status' => OrderEnum::STATUS_PENDING
            ])
            ->where('created_at', '>=', Carbon::now()->subMinutes(1))
            ->exists();
        if ($check) {
            return $this->error('请勿操作频繁，请1分钟后重试！');
        }

        $remark = OrderEnum::TYPE_EXPLAINS[$orderType];
        $orderNo = Order::generateSerialNumber();
        $receipt = [
            'user_id' => auth('jwt')->id(),
            'type' => $orderType,
            'amount' => $chargeFee,
            'order_no' => $orderNo,
            'out_trade_no' => '',
            'status' => OrderEnum::STATUS_PENDING,
            'remark' => $remark,
        ];
        DB::beginTransaction();

        $order = Order::query()->create($receipt);
        $notifyURL = url('payment/wechat/paid-callback');

        try {
            $result = WechatPayPayment::makePrepay([
                'body' => $remark,
                'out_trade_no' => $orderNo,
                'trade_type' => 'APP',
                'openid' => $user->openid,
                'total_fee' => $chargeFee * 100,
                'notify_url' => $notifyURL,
            ]);
            DB::commit();

            return $this->success([
                'order_id' => $order->id,
                'payload' => $result,
                "need_pay" => 1
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e);
            return $this->error("支付参数异常");
        }
    }

    public function paycheck(Request $request)
    {
        $orderId = $request->post('order_id');

        /** @var Order $order */
        $order = Order::query()->find($orderId);

        if (!$order) {
            return $this->error('订单信息不存在');
        }
        $paid = $order->status == OrderEnum::STATUS_PAID;


        return $this->success([
            'order_id' => $orderId,
            'paid' => (int)$paid
        ]);
    }
}
